package com.ruoyi.newRepair.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.newRepair.domain.FaultCategoryStats;
import com.ruoyi.newRepair.domain.RepairOrder;
import com.ruoyi.newRepair.mapper.RepairOrderMapper;
import com.ruoyi.newRepair.service.EquipmentAnalysisService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


// 4. 控制器层
@RestController
@Api(tags = "EquipmentController   api")
//@RequestMapping("/api/wareHouses")
@RequestMapping("/wareHouses")
@RequiredArgsConstructor
@Slf4j
public class EquipmentController extends BaseController {
    @Resource
    private final EquipmentAnalysisService analysisService;

    @Resource
    private final RepairOrderMapper repairOrderMapper;

    //设备完成时长统计图
    @GetMapping("/mtbf")
    public Map<String, Map<String, Object>> getEquipmentStats() {
        return analysisService.getEquipmentStats();
    }

    //帕累托图
    @GetMapping("/NumberOfFailures")
    public Map<String, Object> getFaultAnalysis() {
        List<FaultCategoryStats> stats = analysisService.getFaultCategoryStats();
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("dimensions", Arrays.asList("FaultCategory", "Frequency", "CumulativePercentage"));
        result.put("source", stats);
        return result;
    }

    //设备类型统计故障
    @GetMapping("/NumberOfPower")
    public ResponseEntity<?> getFailureStatistics(@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate, @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {

        // 参数有效性校验
        if (startDate != null && startDate.isAfter(LocalDate.now())) {
            return ResponseEntity.badRequest().body("开始日期不能晚于当前日期");
        }
        if (endDate != null && startDate != null && endDate.isBefore(startDate)) {
            return ResponseEntity.badRequest().body("结束日期不能早于开始日期");
        }

        return ResponseEntity.ok(analysisService.getFailureStatistics(startDate != null ? startDate.toString() : null, endDate != null ? endDate.toString() : null));
    }

    //聚类分析
    @GetMapping("/clusterAnalysis")
    public ResponseEntity<?> getClusterResult() throws Exception {
        return ResponseEntity.ok(analysisService.analyzeClusters());
    }

    //控制图
    @GetMapping("/control")
    public ResponseEntity<?> getControlChartData() {
        return ResponseEntity.ok(analysisService.generateControlChartData());
    }


    // 设备类型统计故障次数柱状图跳转
    @GetMapping("/faultDetails/{deviceType}")
    public ResponseEntity<?> getFaultDetails(@PathVariable String deviceType, @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate, @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {

        // 参数处理
        String startStr = startDate != null ? startDate.toString() : null;
        String endStr = endDate != null ? endDate.toString() : null;

        return ResponseEntity.ok(analysisService.getFailureDetails(deviceType, startStr, endStr));
    }


    @GetMapping("/RepairNumber")
    public ResponseEntity<?> getRepairNumberStatistics() {
        return ResponseEntity.ok(analysisService.getRepairNumberStatistics());
    }


    //    设备编号统计
    @GetMapping("/NumberOfPower/{equipmentNo}")
    public ResponseEntity<?> getDetails(@PathVariable String equipmentNo, @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate, @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {

        // 参数有效性校验
        if (startDate != null && startDate.isAfter(LocalDate.now())) {
            return ResponseEntity.badRequest().body("开始日期不能晚于当前日期");
        }
        if (endDate != null && startDate != null && endDate.isBefore(startDate)) {
            return ResponseEntity.badRequest().body("结束日期不能早于开始日期");
        }

        return ResponseEntity.ok(analysisService.getDetails(equipmentNo, startDate != null ? startDate.toString() : null, endDate != null ? endDate.toString() : null));
    }

    //    设备编号详情
    @GetMapping("/equipmentDetails/{equipmentNo}")
    public ResponseEntity<?> getEquipmentDetails(@PathVariable String equipmentNo, @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate, @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate, @RequestParam(required = false) String completedByName) {
        // 参数有效性校验
        if (startDate != null && startDate.isAfter(LocalDate.now())) {
            return ResponseEntity.badRequest().body("开始日期不能晚于当前日期");
        }
        if (endDate != null && startDate != null && endDate.isBefore(startDate)) {
            return ResponseEntity.badRequest().body("结束日期不能早于开始日期");
        }
//        获取数据

//        获取数据总数
        Long actions = analysisService.getEquipmentNoDetailsActions(equipmentNo,
                startDate != null ? startDate.toString() : null,
                endDate != null ? endDate.toString() : null,
                completedByName);
        startPage();
        List<RepairOrder> dataList = analysisService.getEquipmentNoDetails(
                equipmentNo,
                startDate != null ? startDate.toString() : null,
                endDate != null ? endDate.toString() : null,
                completedByName);

        Map<String, Object> attributes = new LinkedHashMap<>();
        attributes.put("actions", actions);
        attributes.put("data", dataList);

        return ResponseEntity.ok(attributes);
    }

    //    MTTR
    @PostMapping("/MTTR")
    public ResponseEntity<?> countMTTR(
            @RequestBody(required = false) List<String> equipmentIds,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        String startStr = startDate != null ? startDate.toString() : null;
        String endStr = endDate != null ? endDate.toString() : null;
        return ResponseEntity.ok(analysisService.countMTTR(equipmentIds, startStr, endStr));
    }

    //    设备类型查询
    @GetMapping("/equipmentId")
    public ResponseEntity<?> getEquipmentId() {
        log.info("设备编号查询");
        return ResponseEntity.ok(analysisService.getEquipmentId());
    }

    //    MTBF
    @PostMapping("/MTBF")
    public ResponseEntity<?> countMTBF(
            @RequestBody(required = false) List<String> equipmentIds,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        String startStr = startDate != null ? startDate.toString() : null;
        String endStr = endDate != null ? endDate.toString() : null;
        return ResponseEntity.ok(analysisService.countMTBF(equipmentIds, startStr, endStr));
    }

    //    设备编号统计
    @GetMapping("/countE")
    public ResponseEntity<?> getBasicStatistics() {
        log.info("设备编号统计");
        return ResponseEntity.ok(analysisService.countEquipment());
    }

    //    总利用率
    @PostMapping("/countUR")
    public ResponseEntity<?> countUR(
            @RequestBody(required = false) List<String> equipmentIds,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        String startStr = startDate != null ? startDate.toString() : null;
        String endStr = endDate != null ? endDate.toString() : null;
        return ResponseEntity.ok(analysisService.countUR(equipmentIds, startStr, endStr));
    }

    //    总维修时长
    @PostMapping("/countRepair")
    public ResponseEntity<?> countfix(
            @RequestBody(required = false) List<String> equipmentIds,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        String startStr = startDate != null ? startDate.toString() : null;
        String endStr = endDate != null ? endDate.toString() : null;
        return ResponseEntity.ok(analysisService.countfix(equipmentIds, startStr, endStr));
    }

    //    总故障周趋势
    @GetMapping("totalFailure")
    public ResponseEntity<?> totalFailure() {
        log.info("设备编号统计");
        return ResponseEntity.ok(analysisService.totalFailure());
    }

    //    上周设备故障分布图
    @GetMapping("/lastWeek")
    public ResponseEntity<?> getLastWeekFailureDetails() {
        log.info("上周故障详情");
        return ResponseEntity.ok(analysisService.getLastWeekFailureDetails());
    }

    //    具体设备维修单分布
    @GetMapping("/lastWeek/{deviceType}")
    public ResponseEntity<?> getSpecificEquipment(@PathVariable String deviceType) {
        log.info("具体设备维修单分布");
        return ResponseEntity.ok(analysisService.getSpecificEquipment(deviceType));
    }

    //    OEE设备选取
    @GetMapping("/OEquipmentId")
    public ResponseEntity<?> getOEEEquipmentId() {
        log.info("设备编号查询");
        return ResponseEntity.ok(analysisService.getOEEEquipmentId());
    }

    //    OEE统计
    @PostMapping("/OEE")
    public ResponseEntity<?> countOEE(
            @RequestBody(required = false) List<String> machineNos,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        String startStr = startDate != null ? startDate.toString() : null;
        String endStr = endDate != null ? endDate.toString() : null;
        return ResponseEntity.ok(analysisService.countOEE(machineNos, null, startStr, endStr));
    }
}